using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Mobileterminal.Common;
using Mobileterminal.Dtos;
using Newtonsoft.Json;
using Sunny.UI;

namespace Mobileterminal.Forms.Yjb
{
    public partial class MedicineDistributionForm : UIPage
    {
        public MedicineDistributionForm()
        {
            InitializeComponent();
            LoadMedicineDistributionDataAsync();
        }

        private async Task LoadMedicineDistributionDataAsync(string cardNumber = null, string patientName = null)
        {
            try
            {
                // 构建动态查询参数
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(cardNumber))
                    queryParams.Add($"cardNumber={Uri.EscapeDataString(cardNumber)}");
                if (!string.IsNullOrEmpty(patientName))
                    queryParams.Add($"patientName={Uri.EscapeDataString(patientName)}");

                var url = "https://localhost:7224/api/Show/ShowMedicineDistribution";
                if (queryParams.Count > 0)
                    url += "?" + string.Join("&", queryParams);

                var json = await HttpClientHelper.ClientAsync("GET", url);
                var result = JsonConvert.DeserializeObject<Result<List<MedicineDistributionDTO>>>(json);

                if (result.Code == 200)
                {
                    // 设置数据源
                    uiDataGridView1.DataSource = result.Data;
                    
                    // 添加操作列
                    if (!uiDataGridView1.Columns.Contains("操作"))
                    {
                        DataGridViewButtonColumn actionColumn = new DataGridViewButtonColumn();
                        actionColumn.Name = "操作";
                        actionColumn.HeaderText = "操作";
                        actionColumn.Text = "发药";
                        actionColumn.UseColumnTextForButtonValue = true;
                        uiDataGridView1.Columns.Add(actionColumn);
                    }
                }
                else
                {
                    UIMessageTip.ShowError($"加载数据失败: {result.Msg}");
                }
            }
            catch (Exception ex)
            {
                UIMessageTip.ShowError($"发生错误: {ex.Message}");
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            string cardNumber = txtCardNumber.Text.Trim();
            string patientName = txtPatientName.Text.Trim();
            await LoadMedicineDistributionDataAsync(cardNumber, patientName);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtCardNumber.Text = string.Empty;
            txtPatientName.Text = string.Empty;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            txtCardNumber.Text = string.Empty;
            txtPatientName.Text = string.Empty;
            LoadMedicineDistributionDataAsync();
        }

        private async void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == uiDataGridView1.Columns["操作"].Index)
            {
                int medicineDistributionId = Convert.ToInt32(uiDataGridView1.Rows[e.RowIndex].Cells["MedicineDistributionId"].Value);
                string cardNumber = uiDataGridView1.Rows[e.RowIndex].Cells["CardNumber"].Value.ToString();
                string patientName = uiDataGridView1.Rows[e.RowIndex].Cells["PatientName"].Value.ToString();
                string gender = uiDataGridView1.Rows[e.RowIndex].Cells["Gender"].Value.ToString();
                int age = Convert.ToInt32(uiDataGridView1.Rows[e.RowIndex].Cells["Age"].Value);
                string identityNumber = uiDataGridView1.Rows[e.RowIndex].Cells["IdentityNumber"].Value.ToString();

                // 执行删除操作（标记为已删除）
                var delData = new
                {
                    MedicineDistributionId = medicineDistributionId
                };

                var content = new StringContent(
                    JsonConvert.SerializeObject(delData),
                    Encoding.UTF8,
                    "application/json");

                try
                {
                    var json = await HttpClientHelper.ClientAsync("PUT", "https://localhost:7224/api/Yjb/DelMedicineDistribution", false, content);
                    var result = JsonConvert.DeserializeObject<Result<int>>(json);
                    
                    if (result.Code == 200)
                    {
                        UIMessageTip.ShowOk("发药成功！");
                        // 刷新数据
                        await LoadMedicineDistributionDataAsync();
                        
                        // 添加到已发药品表
                        var addInventoryData = new
                        {
                            CardNo = cardNumber,
                            Name = patientName,
                            Sex = gender,
                            YearsOld = age,
                            IdCard = identityNumber,
                            DispenseTime = DateTime.Now,
                            DispenseStatus = "已发药",
                            IsDeleted = false
                        };

                        content = new StringContent(
                            JsonConvert.SerializeObject(addInventoryData),
                            Encoding.UTF8,
                            "application/json");

                        json = await HttpClientHelper.ClientAsync("POST", "https://localhost:7224/api/Yjb/AddMedicineInventory", false, content);
                        result = JsonConvert.DeserializeObject<Result<int>>(json);
                        
                        if (result.Code != 200)
                        {
                            UIMessageTip.ShowError($"添加到已发药品表失败: {result.Msg}");
                        }
                    }
                    else
                    {
                        UIMessageTip.ShowError($"发药失败: {result.Msg}");
                    }
                }
                catch (Exception ex)
                {
                    UIMessageTip.ShowError($"发生错误: {ex.Message}");
                }
            }
        }
    }

    public class MedicineDistributionDTO
    {
        public int MedicineDistributionId { get; set; }
        public string CardNumber { get; set; }
        public string PatientName { get; set; }
        public string Gender { get; set; }
        public int Age { get; set; }
        public string IdentityNumber { get; set; }
        public DateTime PrintTime { get; set; }
        public string PrintStatus { get; set; }
        public bool IsDeleted { get; set; }
    }
} 